import { useToast } from "primevue/usetoast";
import { storeToRefs } from "pinia";
import { useLocalStorage } from "@vueuse/core";
export function useShopList(cartListStore) {
  const toast = useToast();

  const { addToCartList } = cartListStore;
  const { cartList } = storeToRefs(cartListStore);

  const cartListLocalStorage = useLocalStorage("cart-list", []);

  function onClick(product) {
    //判断数组中是否有商品id
    //存在,直接返回
    if (cartList.value.some((item) => Number(item.id) === Number(product.id))) {
      //toast error
      toast.add({
        severity: "error",
        summary: "Error Message",
        detail: "the product is already in the cart",
        life: 3000,
      });
      return;
    }
    //不存在,添加
    addToCartList(product);
    cartListLocalStorage.value = [...cartListLocalStorage.value, product];

    toast.add({
      severity: "success",
      summary: "Success Message",
      detail: "the product has been added to the cart",
      life: 3000,
    });
  }
  return {
    onClick,
  };
}
